<?php
include_once 'send_http_mssage.class.php';
class callback_notify
{
	private $dc=null;
	private $sp_id=null;
	/**
	 * 以后spid即将不作为传入参数，需根据反馈的参数去获取或者方法中
	 * 之后会取消掉，碰到的地方尽量做修正 2016-11-1
	 * @param string $sp_id
	 */
	public function __construct($sp_id=null)
	{
		$this->dc = nl_get_dc(array (
				'db_policy' => NL_DB_WRITE,
				'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
		));
		$this->sp_id = $sp_id;//即将废弃
	}
	
	/**
	 * 媒资上下线反馈给上游  并且修改上下线日志，上下数据状态
	 * @param array $info 反馈数据
	 * @author liangpan
	 * @date 2015-11-26
	 */
	public function unline_notify($info)
	{
		if(empty($info) || !isset($info['cmsresult']) || empty($info['cmsresult']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"接收返回消息有误",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		//解析XML
		$xml_data = np_xml_to_array::parse2($info['cmsresult']);
		if(!isset($xml_data['msgid']) || empty($xml_data['msgid']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"消息id为空",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		if(!isset($xml_data['state']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"状态未设置",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		//$nns_status = (isset($xml_data['state']) && $xml_data['state'] == 1) ? '2' : '3';
		$result_log=nl_asset_online_log::query_by_id($this->dc,$xml_data['msgid']);
		if($result_log['ret'] !=0)
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,$result_log['reason'],'',VIDEO_TYPE_VIDEO);
			return ;
		}
		if(!isset($result_log['data_info'][0]) || empty($result_log['data_info'][0]) || !is_array($result_log['data_info'][0]))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"未查到上下线日志数据",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		$this->sp_id = $result_log['data_info'][0]['nns_org_id'];
		
		$up_message_id = $result_log['data_info'][0]['nns_message_id'];
		$asset_online_id = $result_log['data_info'][0]['nns_asset_online_id'];
		$callback_content = isset($xml_data['msg']) ? $xml_data['msg'] : '';
		
		$params = array(
				//'nns_status'=>$nns_status,
				'nns_callback_content'=>$info['cmsresult'],
				'nns_reason'=>$callback_content				
		);
		
		if(isset($xml_data['state']) && $xml_data['state'] == 1)
		{
			$params['nns_status'] = 2;
			$result_online_log = nl_asset_online_log::update($this->dc,$params,array('nns_id'=>$xml_data['msgid']));
			$result = array('ret' => 0);
		}
		else
		{
			$params['nns_status'] = 3;
			$result_online_log=nl_asset_online_log::update($this->dc,$params,array('nns_id'=>$xml_data['msgid']));
			$result = array('ret' => 1);
		}
		
// 		if($result_online_log['ret'] != 0)
// 		{
		nn_log::write_log_message(LOG_MODEL_NOTIFY,"ID为【{$xml_data['msgid']}】执行上下线日志修改:".var_export($result_online_log,true),$this->sp_id,VIDEO_TYPE_VIDEO);
// 		}
		//获取SP配置
		$sp_config = sp_model::get_sp_config($this->sp_id);
		
		if(!isset($sp_config['online_notify_enabled']) || intval($sp_config['online_notify_enabled']) === 0)
		{
			if(!isset($sp_config['online_notify_url']) || strlen($sp_config['online_notify_url']) <= 0)
			{
				nn_log::write_log_message(LOG_MODEL_NOTIFY,"SP未配置反馈地址",$this->sp_id,VIDEO_TYPE_VIDEO);
				//return ;
			}
			else 
			{
				$import_url = $sp_config['online_notify_url'];
				//1 成功，其他失败
				$str_xml = '<xmlresult><msgid>'.$up_message_id.'</msgid><siteid></siteid><state>'.$xml_data['state'].'</state><msg>'.$params['nns_reason'].'</msg></xmlresult>';
				nn_log::write_log_message(LOG_MODEL_NOTIFY,"异步反馈上游，反馈数据为:".var_export($str_xml,true),$this->sp_id,VIDEO_TYPE_VIDEO);
				$send_http_mssage = new send_http_mssage($import_url,$this->sp_id);
				$result = $send_http_mssage->up_callback_notify($str_xml, $up_message_id);
		        $result = json_decode($result,true);
		        nn_log::write_log_message(LOG_MODEL_NOTIFY,"异步反馈上游，反馈结果为:".var_export($result,true),$this->sp_id,VIDEO_TYPE_VIDEO);
		        //后期将增加CP上游的反馈，需把反馈地址移入CP配置中，但整体的上下线配置还是在SP中
			}
		}
        if($result['ret'] == 0)
		{
			//下游操作成功删除队列
			$result_online = nl_asset_online::del_by_id($this->dc,$asset_online_id);
		}
		else
		{				
			//先检查队列中是否存在相同的  等待注入、等待反馈的任务,存在同一个媒资，相同操作的任务，需清理当前任务
			$queue_line = nl_asset_online::query_by_id($this->dc, $asset_online_id);
			$same_params = array(
				'nns_import_id' => $queue_line['data_info'][0]['nns_import_id'],
				'nns_category_id' => $queue_line['data_info'][0]['nns_category_id'],
				'nns_org_id' => $queue_line['data_info'][0]['nns_org_id'],
				'nns_cp_id' => $queue_line['data_info'][0]['nns_cp_id'],
				'nns_status' => array(1,3),
				'nns_id not' => array($asset_online_id),//排除自己
			);
			$same_re = nl_asset_online::check_online_queue($this->dc, $same_params);
			if($same_re['ret'] != 0)
			{
				nn_log::write_log_message(LOG_MODEL_NOTIFY,"检查队列中是否存在相同的  等待注入、等待反馈的任务".$same_re['reason'],$this->sp_id,VIDEO_TYPE_VIDEO);
				return ;
			}
			if($same_re['data_info']['count'] > 0)
			{
				$result_online = nl_asset_online::del_by_id($this->dc,$asset_online_id);
			}
			else
			{
				//操作失败
				$result_online=nl_asset_online::update($this->dc,array('nns_status'=>4),array('nns_id'=>$asset_online_id),'nns_fail_time=nns_fail_time+1');
			}
		}
		if($result_online['ret'] != 0)
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,$result_online['reason'],$this->sp_id,VIDEO_TYPE_VIDEO);
		}
		return;
	}
	/**
	 * 透传队列回调地址
	 * @param $info 反馈数组 array('cmsresult')
	 */
	public function pass_queue_notify($info)
	{
		if(empty($info) || !isset($info['cmsresult']) || empty($info['cmsresult']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"接收返回消息有误",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		//解析XML
		$xml_data = np_xml_to_array::parse2($info['cmsresult']);
		if(!isset($xml_data['msgid']) || empty($xml_data['msgid']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"融合消息id为空",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		if(!isset($xml_data['bkmsgid']) || empty($xml_data['bkmsgid']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"播控消息id为空",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		if(!isset($xml_data['state']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"状态反馈错误",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		//根据播控消息ID即当前透传队列的GUID查询相关信息
		$result = nl_pass_queue::query_by_id($this->dc, $xml_data['bkmsgid']);
		if($result['ret'] != 0)
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,'数据库查询失败','',VIDEO_TYPE_VIDEO);
			return ;
		}
		if(!isset($result['data_info'][0]) || empty($result['data_info'][0]) || !is_array($result['data_info'][0]))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"未查到透传队列数据",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		$queue_info = $result['data_info'][0];
		$this->sp_id = $queue_info['nns_org_id'];
		//获取CP配置信息
		$cp_info = nl_cp::query_by_id($this->dc, $queue_info['nns_cp_id']);
		if($cp_info['ret'] != 0)
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,$cp_info['reason'],'',VIDEO_TYPE_VIDEO);
			return ;
		}
		if(!isset($cp_info['data_info']) || empty($cp_info['data_info']) || !is_array($cp_info['data_info']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"未查到CP配置信息",'',VIDEO_TYPE_VIDEO);
			return ;
		}
		$cp_config = json_decode($cp_info['data_info']['nns_config'],true);
		nn_log::write_log_message(LOG_MODEL_NOTIFY,var_export($cp_config,true),'',VIDEO_TYPE_VIDEO);
		$params = array('nns_modify_time' => date('Y-m-d H:i:s',time()));
		$params['nns_result_desc'] = $xml_data['msg'];
		if(isset($xml_data['state']) && $xml_data['state'] == 1)
		{
			$params['nns_status'] = 0;
			nl_pass_queue::modify($this->dc,$params,array('nns_id' => $xml_data['bkmsgid']));
		}
		else
		{
			$params['nns_status'] = 3;
			nl_pass_queue::modify($this->dc,$params,array('nns_id' => $xml_data['bkmsgid']));
		}
		$str_message = $xml_data['msg'];
		if(isset($cp_config['site_id']) && strlen($cp_config['site_id']) > 0 && isset($cp_config['site_callback_url']) && strlen($cp_config['site_callback_url']) > 0)
		{
			$xml_info = array(
					'msgid' => $queue_info['nns_message_id'],
					'state' => $xml_data['state'],
					'msg' => $str_message,
					'site_id' => $cp_config['site_id']
			);
			$str_xml = $this->_build_notify($xml_info);
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"异步反馈上游，反馈数据为:".var_export($str_xml,true),$this->sp_id,VIDEO_TYPE_VIDEO);
			$send_http_mssage = new send_http_mssage($cp_config['site_callback_url'],$this->sp_id);
			$result = $send_http_mssage->up_callback_notify($str_xml, $queue_info['nns_message_id']);
			$result = json_decode($result,true);
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"异步反馈上游，反馈结果为:".var_export($result,true),$this->sp_id,VIDEO_TYPE_VIDEO);
		}
	}
	/**
	 * 组装反馈的XML
	 * @param $params
	 */
	private function _build_notify($params)
	{
		if(!is_array($params) || empty($params))
		{
			return ;
		}
		$dom = new DOMDocument('1.0', 'utf-8');
		$xmlresult = $dom->createElement('xmlresult');
		$dom->appendChild($xmlresult);
		foreach ($params as $key=>$value)
		{
			$$key = $dom->createElement($key);
			$xmlresult->appendchild($$key);
			if(!empty($value) && is_array($value))
			{
				foreach ($value as $k=>$val)
				{
					$$k = $dom->createElement($k);
					$$key->appendchild($$k);
					//创建元素值
					$content = $dom->createTextNode($val);
					$$k->appendchild($content);
				}
			}
			else
			{
				//创建元素值
				$text = $dom->createTextNode($value);
				$$key->appendchild($text);
			}
		}
		return $dom->saveXML();
	}

	public function pass_queue_notify_v2($info,$format='xml')
	{
		if(empty($info) || !isset($info['ret']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"接收返回消息有误",$this->sp_id,LOG_PASS_QUEUE_MODEL);
			return ;
		}
		//根据播控消息ID即当前透传队列的GUID查询相关信息
		$result = nl_pass_queue::query_by_id($this->dc, $info['bkmsgid']);
		if($result['ret'] != 0)
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,'数据库查询失败',$this->sp_id,LOG_PASS_QUEUE_MODEL);
			return ;
		}
		if(!isset($result['data_info'][0]) || empty($result['data_info'][0]) || !is_array($result['data_info'][0]))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"未查到透传队列数据",$this->sp_id,LOG_PASS_QUEUE_MODEL);
			return ;
		}
		$queue_info = $result['data_info'][0];
		$this->sp_id = $queue_info['nns_org_id'];
		//获取CP配置信息
		$cp_info = nl_cp::query_by_id($this->dc, $queue_info['nns_cp_id']);
		if($cp_info['ret'] != 0)
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,$cp_info['reason'],$this->sp_id,LOG_PASS_QUEUE_MODEL);
			return ;
		}
		if(!isset($cp_info['data_info']) || empty($cp_info['data_info']) || !is_array($cp_info['data_info']))
		{
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"未查到CP配置信息",$this->sp_id,LOG_PASS_QUEUE_MODEL);
			return ;
		}
		$cp_config = json_decode($cp_info['data_info']['nns_config'],true);
		nn_log::write_log_message(LOG_MODEL_NOTIFY,var_export($cp_config,true),$this->sp_id,LOG_PASS_QUEUE_MODEL);
		$params = array('nns_modify_time' => date('Y-m-d H:i:s',time()));
		$params['nns_result_desc'] = $info['reason'];
		$info['ret'] = $info['ret'] == 0 ? "1" : "0" ;
		$str_message = $info['reason'];
//		var_dump($cp_config);die;

		if(isset($cp_config['site_id']) && strlen($cp_config['site_id']) > 0 && isset($cp_config['site_callback_url']) && strlen($cp_config['site_callback_url']) > 0)
		{

			if($format == 'json')
			{
				$arr_xml = array
				(
					'pushCode'=>$queue_info['nns_message_id'],
					'state'=>$info['ret'],
					'feedbackContent' =>urlencode($info['reason'])
				);
		//		var_dump($arr_xml);die;
		//		$str_xml = json_encode($arr_xml,JSON_UNESCAPED_UNICODE);
				$str_xml =urldecode(json_encode($arr_xml));
			}
			else
			{
				$xml_info = array(
					'msgid' => $queue_info['nns_message_id'],
					'state' => $info['ret'],
					'msg' => $str_message,
					'site_id' => $cp_config['site_id']
				);
				$str_xml = $this->_build_notify($xml_info);
			}
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"异步反馈上游，反馈数据为:".$str_xml,$this->sp_id,LOG_PASS_QUEUE_MODEL);
			$send_http_mssage = new send_http_mssage($cp_config['site_callback_url'],$this->sp_id);
			$result = $send_http_mssage->up_callback_notify_v2($str_xml, $queue_info['nns_message_id'],$format);
			$result = json_decode($result,true);
			nn_log::write_log_message(LOG_MODEL_NOTIFY,"异步反馈上游，反馈结果为:".var_export($result,true),$this->sp_id,LOG_PASS_QUEUE_MODEL);
		}
	}
}
